<?php

namespace Cyfy\Modules\Videos;
class Module extends \Cyfy\Module
{
    const PATH = "galerie/videogalerie";
    
    static function ajax($name)
    {
        switch($name)
        {
            case "deleteVideo":
                if(!is_numeric($_POST["vid"])) return "";
                return self :: ajaxDeleteVideo($_POST["vid"]);
                
            case "editVideo":
                if(!is_numeric($_POST["vid"])) return "";
                return self :: ajaxEditVideo($_POST["vid"]);
            
            case "getVideo":
                if(!is_numeric($_POST["vid"])) return "";
                return self :: ajaxGetVideo($_POST["vid"]);
            
            case "videos":
                return self :: ajaxVideos();
        }
    
    }
    

	static function get($name)
	{	
        \Cyfy\Template :: setTitle(self :: t(20));
		if($name == "video"){
            return  "<h2>" . self :: t(20) . "</h2>\n" . self :: ajaxGetVideo(\Cyfy\Cyfy :: arg(2));
        }
        
        
		if($name != "main") return false;
        
        if(\Cyfy\Cyfy ::  permission("Videos", "add and delete")){
            $form = new Forms\Add();
            
            $c = new \Cyfy\Modules\Objects\Collapsible();
            $c -> setData(self :: t(10), $form -> show(), true);
            $output .= $c -> show();
        }
        $output .= "<h2>" . self :: t(20) . "</h2>\n";
        $output .= "<div id=\"videos\">";
        $output .= self :: ajaxVideos();
        $output .= "</div>";

        return $output;
	}
	
	static private function ajaxDeleteVideo($vid)
    {
        if(!\Cyfy\Cyfy :: Permission("Videos", "add and delete")){
            return false;
        }

		$result = \dibi :: query("SELECT * FROM [:cyfy:Videos] WHERE [vid] = %i LIMIT 1", $vid);
		
        if(!count($result)) return false;
		
        $v = $result -> fetch();
        \dibi :: query("DELETE FROM [:cyfy:Videos] WHERE [vid] = %i LIMIT 1", $vid);
        \Cyfy\Message :: set(self :: t(41, array($v["title"])));
        return self :: ajaxVideos();
	}

	
    static private function ajaxEditVideo($vid)
    {
        if(!\Cyfy\Cyfy ::  permission("Videos", "add and delete")){
            return false;
        }

		$result = \dibi :: query("SELECT * FROM [:cyfy:Videos] WHERE [vid] = %i LIMIT 1", $vid);
		// not dound
        if(!count($result)) 
        {
            \Cyfy\Message :: set(self :: t(50), \Cyfy\Message::WARNING);
            return false;
        }
        
        $v = $result -> fetch();
        
        // VIDEO LINK FORMAT
        switch($v["type"])
        {
            case "youtube":
                $v["value"] = "http://www.youtube.com/watch?v=" . $v["value"];
                break;
            case "vimeo":
                $v["value"] = "http://vimeo.com/" . $v["value"];
                break;
        }
        
        
        // form
        $form = new Forms\Edit();
        $form -> SetData($v);
        $form -> SetTemp("vid", $v["vid"]);
        return "<hr />" . $form -> show() . "<hr />";
        
        return self :: ajaxVideos();
	}
    
    static private function ajaxGetVideo($vid)
    {
        $result = \dibi :: query("SELECT * FROM [:cyfy:Videos] WHERE [vid] = %i LIMIT 1", $vid);
		// not dound
        if(!count($result)) 
        {
            \Cyfy\Message :: set(self :: t(50), \Cyfy\Message::WARNING);
            return false;
        }        
		return self :: videoDetail((array) $result -> fetch());
	}

	
	static private function ajaxVideos()
    {
       
        $result = \dibi :: query("SELECT * FROM [:cyfy:Videos] ORDER BY [vid] DESC");
        if(!count($result)) 
        {
            return \Cyfy\Message :: get(self :: t(30), \Cyfy\Message::WARNING);
        }        
		
        foreach($result as $v)
        {
            $output .= "<div id=\"videoFrame-{$v["vid"]}\">\n";
            $output .= self :: videoDetail((array) $v);
            $output .= "</div>\n";
        }
        return $output;
    }
	
	static private function videoDetail($v)
	{
    
		$output = "<h3><a href=\"" . \Cyfy\Cyfy :: getPath(self :: PATH . "/" . $v["vid"]) . "\">" . $v["title"] . "</a></h3><p>{$v["description"]}</p><div class=\"video-frame\">";
			
        switch($v["type"])
        {
            //youtube
            case "youtube":
                $output .= "<object width=\"480\" height=\"385\"><param name=\"movie\" value=\"http://www.youtube.com/v/{$v["value"]}&hl=cs_CZ&fs=1&rel=0\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.youtube.com/v/{$v["value"]}&hl=cs_CZ&fs=1&rel=0\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"480\" height=\"385\"></embed></object>";
                break;
            
            // vimeo
            case "vimeo":
                $output .= "<object width=\"480\" height=\"385\"><param name=\"allowfullscreen\" value=\"true\" /><param name=\"allowscriptaccess\" value=\"always\" /><param name=\"movie\" value=\"http://vimeo.com/moogaloop.swf?clip_id={$v["value"]}&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;fullscreen=1\" /><embed src=\"http://vimeo.com/moogaloop.swf?clip_id={$v["value"]}&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;fullscreen=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" allowscriptaccess=\"always\" width=\"480\" height=\"385\"></embed></object>";	
                break;
        }
        $output .= "</div>";
        if(\Cyfy\Cyfy ::  permission("Videos", "add and delete"))
        {
            \Cyfy\Modules\Forms\Module :: RunOnce();
            $output .= "<div class=\"form-buttons\">\n";
            $output .= "<input type=\"submit\" class=\"button-normal\" value=\"" . self :: t(61, array($v["title"])) . "\" onclick=\"Cyfy.ajax('Videos', 'editVideo', '#videoFrame-{$v["vid"]}', 'vid={$v["vid"]}') \">\n";
                //delete
            $output .= "<input type=\"submit\" class=\"button-warning\" value=\"" . self :: t(71, array($v["title"])) . "\" onclick=\"if(confirm('" . self :: t(80) . "')){ Cyfy.ajax('Videos', 'deleteVideo', '#videos', 'vid={$v["vid"]}') }\">\n";
            $output .= "</div>\n";
        }
        
		return $output;
	}
    
    
    
    static function parseUrl($url)
    {
        // if not http, try to insert http
		if(strpos($url, "http://") === false){
			$url = "http://" . $url;
		}
		
		$parsed = parse_url($url);
		$error = false;
		
		// if youtube.com
		if(strpos($parsed["host"], "youtube.com") !== false){
		
			// find /watch
			if($parsed["path"] == "/watch"){
			
				// search for v=XXXXX
				$parsedQuery = self :: parseQuery($parsed["query"]);
				
				// if exists
				if($parsedQuery["v"]){
                    $vid = array("type"=> "youtube", "value" => $parsedQuery["v"]);
					return $vid;
				}
			}
		// if vimeo.com
		}else if(strpos($parsed["host"], "vimeo.com") !== false){
		
			$parsedQuery = explode("/", $parsed["path"]);
			
			// if parameter 2 is a number
			if(preg_match("/^[0-9]+$/", $parsedQuery[1])){
				$vid = array("type"=> "vimeo", "value" => $parsedQuery[1]);
                return $vid;
			}
		}
        
        return false;
    }
    
    static private function parseQuery($var)
	{
		$var = html_entity_decode($var);
		$var = explode('&', $var);
		$arr = array();

		foreach($var as $val)
		{
			$x = explode('=', $val);
			$arr[$x[0]] = $x[1];
		}
		
		return $arr;
	}
    
	
}
